import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:talk/api/AlarmApi.dart';
import 'package:talk/pages/device/model/DeviceAlarm.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/CustomSwitch.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/Device.dart';

class DeviceAlarmInfoPage extends StatefulWidget {
  const DeviceAlarmInfoPage({
    super.key,
    this.deviceId,
    this.deviceAlarm,
  });

  final int? deviceId;
  final DeviceAlarm? deviceAlarm;

  @override
  State<DeviceAlarmInfoPage> createState() => _DeviceAlarmInfoPageState();
}

class _DeviceAlarmInfoPageState extends State<DeviceAlarmInfoPage> {
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();
  late int _deviceId;
  late int _camId;
  DeviceAlarm? _deviceAlarm;
  late int _ioSelect;

  // 移动侦测开关状态
  late int interComMotionDetection;
  // 移动侦测设置开关状态
  late int interComMotionDetectionSetting;
  // 报警录制开关状态
  late int interAlarmRecord;
  // 防区设置开关状态
  late int interDefenseSetting;

  // 移动侦测时间段数据
  List<dynamic> _motionDetectionTimeList = [];
  // 控制“移动侦测时间段设置”表格是否显示
  bool _showMotionDetectionTimeTable = false;

  // 防区设置数据
  List<dynamic> _defenseSettingList = [];
  // 控制“防区设置”表格是否显示
  bool _showDefenseSettingTable = false;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _deviceAlarm = widget.deviceAlarm!;
    _camId = widget.deviceAlarm!.camId!;

    interComMotionDetectionSetting = _deviceAlarm?.motionDetectionSetting ?? 0;
    interAlarmRecord = _deviceAlarm?.alarmRecord ?? 0;
    interDefenseSetting = _deviceAlarm?.defenseSetting ?? 0;

    // 初始加载数据
    _fetchMotionDetectionTimeData(interComMotionDetectionSetting);
    _fetchDefenseSettingData(interDefenseSetting);
  }


  // 获取移动侦测时间段数据
  void _fetchMotionDetectionTimeData(int motionDetectionValue) async {
    if (motionDetectionValue == 1) {
      try {
        final getInfoFrom = {
          "camId": _camId,
          "weekIlk": 0,
        };

        final response = await _alarmApi.getAlarmInfo(getInfoFrom);
        if (response.code == 200) {
          setState(() {
            _motionDetectionTimeList = response.data;
            _showMotionDetectionTimeTable = true;
          });
        } else {
          debugPrint("获取移动侦测时间段数据失败，code: ${response.getMsg}");
          setState(() {
            _showMotionDetectionTimeTable = false;
          });
        }
      } catch (e) {
        debugPrint("获取移动侦测时间段数据异常");
        setState(() {
          _showMotionDetectionTimeTable = false;
        });
      }
    } else {
      setState(() {
        _showMotionDetectionTimeTable = false;
      });
    }
  }


  // 获取防区设置数据
  void _fetchDefenseSettingData(int defenseSettingValue) async {
    if (defenseSettingValue == 1) {
      final getInfoFrom = {
        "camId": _camId,
        "weekIlk": 1,
      };
      try {
        final response = await _alarmApi.getAlarmInfo(getInfoFrom);
        if (response.code == 200) {
          setState(() {
            _defenseSettingList = response.data;
            _showDefenseSettingTable = true;
          });
        } else {
          debugPrint("获取防区设置数据失败，code: ${response.getMsg}");
          setState(() {
            _showDefenseSettingTable = false;
          });
        }
      } catch (e) {
        debugPrint("获取防区设置数据异常");
        setState(() {
          _showDefenseSettingTable = false;
        });
      }
    } else {
      setState(() {
        _showDefenseSettingTable = false;
      });
    }
  }


  //移动侦测
  Future<void> _updateMotionDetectionSetting(int motionDetectionSetting) async {
    final toUpdate = {
      "camId": _camId,
      "motionDetectionSetting": motionDetectionSetting,
      "type": 1,
      "deviceId": _deviceId,
    };
    final response = await _alarmApi.updateMotionAndDefenseButton(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }
  //防区
  Future<void> _updateDefenseSetting(int defenseSetting) async {
    final toUpdate = {
      "camId": _camId,
      "defenseSetting": defenseSetting,
      "type": 2,
      "deviceId": _deviceId,
    };
    final response = await _alarmApi.updateMotionAndDefenseButton(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }
  //报警录制
  Future<void> _updateAlarmRecordSetting(int alarmRecord) async {
    final toUpdate = {
      "camId": _camId,
      "alarmRecord": alarmRecord,
      "type": 3,
      "deviceId": _deviceId,
    };
    final response = await _alarmApi.updateMotionAndDefenseButton(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }
  //灵敏度
  Future<void> _updateSensitivitySetting(int sensitivity) async {
    final toUpdate = {
      "camId": _camId,
      "sensitivity": sensitivity,
      "type": 4,
      "deviceId": _deviceId,
    };
    final response = await _alarmApi.updateMotionAndDefenseButton(toUpdate);
    if (response.code == 200) {
      setState(() {

      });
    } else {
      Toast.show(AppLocale.text('s_update500') + "${response.getMsg ?? AppLocale.text('s_not500')}");
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: _deviceAlarm?.camName ?? AppLocale.text('d_gaojingxiangqing'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          children: [
            // 移动侦测 ItemView
            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_yidongzhence'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  CustomSwitch(
                    value: _deviceAlarm?.motionDetectionSetting ?? 0,
                    size: 25.0,
                    onChanged: (newValue) {
                      setState(() {
                        _deviceAlarm?.motionDetectionSetting = newValue;
                        interComMotionDetectionSetting = newValue;
                        _fetchMotionDetectionTimeData(newValue);

                        _updateMotionDetectionSetting(newValue);
                      });
                    },
                    activeBackgroundColor: Colors.green,
                    inactiveBackgroundColor: Colors.grey[300]!,
                  ),
                ],
              ),

              borderRadius: 8,
              onTap: () {
                if(_showMotionDetectionTimeTable){
                  final deviceAlarmJson = json.encode(_deviceAlarm?.toJson());
                  final encodedDeviceAlarm = Uri.encodeComponent(deviceAlarmJson);
                  NavigatorUtils.push(
                    context,
                    '${XDeviceRouter.deviceAlarmMontionPage}?deviceId=$_deviceId&deviceAlarm=$encodedDeviceAlarm',
                  );
                }
              },
            ),



            // 报警录制 ItemView
            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_baojingruzhi'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  CustomSwitch(
                    value: _deviceAlarm?.alarmRecord ?? 0,
                    size: 25.0,
                    onChanged: (newValue) {
                      setState(() {
                        _deviceAlarm?.alarmRecord = newValue;
                        interAlarmRecord = newValue;

                        _updateAlarmRecordSetting(newValue);
                      });
                    },
                    activeBackgroundColor: Colors.green,
                    inactiveBackgroundColor: Colors.grey[300]!,
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {

              },
            ),




            // 灵敏度 ItemView
            ItemView(
              width: double.infinity,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_lingmingdu'),
                    style: TextStyle(
                      fontSize: 15.0,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {

                // dynamic ioSelect = 1;
                dynamic ioSelect = _deviceAlarm?.sensitivity;

                // 选项列表（label 是显示文案，value 是实际值）
                List<Map<String, dynamic>> ioList = [
                  {'label': AppLocale.text('d_di'), 'value': 0},
                  {'label': AppLocale.text('d_zhong'), 'value': 1},
                  {'label': AppLocale.text('d_gao'), 'value': 2},
                ];

                showModalBottomSheet(
                  context: context,
                  backgroundColor: Colors.transparent,
                  builder: (BuildContext dialogContext) {
                    return CustomBottomPicker(
                      title: AppLocale.text('d_shiqushezhi'),
                      height: 300,
                      list: ioList,
                      selectedColor: Colors.blue,
                      backgroundColor: Colors.white,
                      initialValue: ioSelect,
                      //圆圈样式
                      selectedShapeType: SelectedShapeType.hollowCircle,
                      onSelect: (newValue) {
                        // 选中值变化时的回调，可在此更新页面状态
                        setState(() {
                          // 示例：如果需要把 newValue 存到 _device 或其他变量，可自行处理
                          // _device.someProperty = newValue;
                          // 更新假数据
                          ioSelect = newValue;
                          _deviceAlarm?.sensitivity = ioSelect;
                          print(ioSelect);

                          _updateSensitivitySetting(ioSelect);
                        });
                      },
                    );
                  },
                );



              },
            ),





            // 防区设置 ItemView
            ItemView(
              width: 400,
              height: 50,
              leftPadding: 10,
              rightPadding: 20,
              leftWidget: Row(
                children: [
                  SizedBox(width: 10),
                  Text(
                    AppLocale.text('d_fangqushezhi'),
                    style: TextStyle(fontSize: 15.0, color: Colors.black),
                  ),
                ],
              ),
              rightWidget: Row(
                children: [
                  CustomSwitch(
                    value: _deviceAlarm?.defenseSetting ?? 0,
                    size: 25.0,
                    onChanged: (newValue) {
                      setState(() {
                        _deviceAlarm?.defenseSetting = newValue;
                        interDefenseSetting = newValue;
                        _fetchDefenseSettingData(newValue);

                        _updateDefenseSetting(newValue);
                      });
                    },
                    activeBackgroundColor: Colors.green,
                    inactiveBackgroundColor: Colors.grey[300]!,
                  ),
                ],
              ),
              borderRadius: 8,
              onTap: () {
                if(_showDefenseSettingTable){
                  final deviceAlarmJson = json.encode(_deviceAlarm?.toJson());
                  final encodedDeviceAlarm = Uri.encodeComponent(deviceAlarmJson);
                  NavigatorUtils.push(
                    context,
                    '${XDeviceRouter.deviceAlarmDefensePage}?deviceId=$_deviceId&deviceAlarm=$encodedDeviceAlarm',
                  );
                }
              },
            ),



            // const SizedBox(height: 15),
            // // 移动侦测时间段设置表格
            // if (_showMotionDetectionTimeTable)
            //   Container(
            //     width: 400,
            //     margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
            //     padding: const EdgeInsets.all(10),
            //     decoration: BoxDecoration(
            //       borderRadius: BorderRadius.circular(8), // 增加圆角半径
            //       color: Colors.white,
            //     ), // 移除了boxShadow
            //     child: Column(
            //       crossAxisAlignment: CrossAxisAlignment.start,
            //       children: [
            //         const Padding(
            //           padding: EdgeInsets.only(left: 10, bottom: 10),
            //           child: Text(
            //             "移动侦测时间段设置",
            //             style: TextStyle(
            //               fontSize: 16,
            //               fontWeight: FontWeight.bold,
            //             ),
            //           ),
            //         ),
            //         ListView.builder(
            //           shrinkWrap: true,
            //           physics: const NeverScrollableScrollPhysics(),
            //           itemCount: _motionDetectionTimeList.length,
            //           itemBuilder: (context, index) {
            //             var item = _motionDetectionTimeList[index];
            //             return GestureDetector(
            //               onTap: () => _onMotionTimeItemTap(item),
            //               child: Container(
            //                 margin: const EdgeInsets.symmetric(vertical: 5),
            //                 padding: const EdgeInsets.all(10),
            //                 decoration: const BoxDecoration(
            //                   color: Colors.white, // 移除了灰色背景
            //                 ),
            //                 child: Row(
            //                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //                   children: [
            //                     Column(
            //                       crossAxisAlignment: CrossAxisAlignment.start,
            //                       children: [
            //                         Text(
            //                           "${item['startTime']} - ${item['endTime']}",
            //                           style: const TextStyle(
            //                             fontSize: 15.0,
            //                             color: Colors.grey,
            //                           ),
            //                         ),
            //                         Text(
            //                           _formatWeekText(item['week'] ?? ''), // 调用工具方法
            //                           style: const TextStyle(
            //                             fontSize: 12.0,
            //                             color: Colors.grey,
            //                           ),
            //                         ),
            //                       ],
            //                     ),
            //                     CustomSwitch(
            //                       value: item['weekType'] ?? 0,
            //                       size: 25.0,
            //                       onChanged: (newValue) => _onMotionSwitchChanged(index, newValue),
            //                       activeBackgroundColor: Colors.green,
            //                       inactiveBackgroundColor: Colors.grey[300]!,
            //                     ),
            //                   ],
            //                 ),
            //               ),
            //             );
            //           },
            //         ),
            //       ],
            //     ),
            //   ),
            // // 防区设置表格
            // if (_showDefenseSettingTable)
            //   Container(
            //     width: 400,
            //     margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
            //     padding: const EdgeInsets.all(10),
            //     decoration: BoxDecoration(
            //       color: Colors.white,
            //       borderRadius: BorderRadius.circular(8), // 增加圆角半径
            //     ), // 移除了boxShadow
            //     child: Column(
            //       crossAxisAlignment: CrossAxisAlignment.start,
            //       children: [
            //         const Padding(
            //           padding: EdgeInsets.only(left: 10, bottom: 10),
            //           child: Text(
            //             "防区设置",
            //             style: TextStyle(
            //               fontSize: 16,
            //               fontWeight: FontWeight.bold,
            //             ),
            //           ),
            //         ),
            //         ListView.builder(
            //           shrinkWrap: true,
            //           physics: const NeverScrollableScrollPhysics(),
            //           itemCount: _defenseSettingList.length,
            //           itemBuilder: (context, index) {
            //             var item = _defenseSettingList[index];
            //             return GestureDetector(
            //               onTap: () => _onDefenseItemTap(item),
            //               child: Container(
            //                 margin: const EdgeInsets.symmetric(vertical: 5),
            //                 padding: const EdgeInsets.all(10),
            //                 decoration: const BoxDecoration(
            //                   color: Colors.white, // 移除了灰色背景
            //                 ),
            //                 child: Row(
            //                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
            //                   children: [
            //                     Column(
            //                       crossAxisAlignment: CrossAxisAlignment.start,
            //                       children: [
            //                         Text(
            //                           "${item['startTime']} - ${item['endTime']}",
            //                           style: const TextStyle(
            //                             fontSize: 15.0,
            //                             color: Colors.grey,
            //                           ),
            //                         ),
            //                         Text(
            //                           _formatWeekText(item['week'] ?? ''), // 调用工具方法
            //                           style: const TextStyle(
            //                             fontSize: 12.0,
            //                             color: Colors.grey,
            //                           ),
            //                         ),
            //                       ],
            //                     ),
            //                     CustomSwitch(
            //                       value: item['weekType'] ?? 0,
            //                       size: 25.0,
            //                       onChanged: (newValue) => _onDefenseSwitchChanged(index, newValue),
            //                       activeBackgroundColor: Colors.green,
            //                       inactiveBackgroundColor: Colors.grey[300]!,
            //                     ),
            //                   ],
            //                 ),
            //               ),
            //             );
            //           },
            //         ),
            //       ],
            //     ),
            //   ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  // 移动侦测时间段项点击事件处理
  void _onMotionTimeItemTap(dynamic item) {
    // debugPrint("点击了移动侦测时间段 - weekId: ${item['weekId']}");
    // debugPrint("详细信息: ${item['week']} ${item['startTime']}-${item['endTime']}");
    // NavigatorUtils.push(
    //   context,
    //   '${XDeviceRouter.dataSelectPage}?camId=$_camId&weekId=${item['weekId']}',
    // );
    final encodedweek = Uri.encodeComponent(item['week']);
    final encodedstartTime = Uri.encodeComponent(item['startTime']);
    final encodedendTime = Uri.encodeComponent(item['endTime']);

    NavigatorUtils.push(
      context,
      '${XDeviceRouter.dataSelectPage}?camId=$_camId'
          '&weekId=${item['weekId']}&week=$encodedweek'
          '&startTime=$encodedstartTime&endTime=$encodedendTime',
    );
  }

  // 移动侦测开关状态变化处理
  void _onMotionSwitchChanged(int index, int newValue) {
    setState(() {
      _motionDetectionTimeList[index]['weekType'] = newValue;
    });
    debugPrint("移动侦测时间段开关状态已更新为: $newValue");
  }

  // 防区设置项点击事件处理
  void _onDefenseItemTap(dynamic item) {
    final encodedweek = Uri.encodeComponent(item['week']);
    final encodedstartTime = Uri.encodeComponent(item['startTime']);
    final encodedendTime = Uri.encodeComponent(item['endTime']);

    NavigatorUtils.push(
      context,
      '${XDeviceRouter.dataSelectPage}?camId=$_camId'
          '&weekId=${item['weekId']}&week=$encodedweek'
          '&startTime=$encodedstartTime&endTime=$encodedendTime',
    );
  }

  // 防区设置开关状态变化处理
  void _onDefenseSwitchChanged(int index, int newValue) {
    setState(() {
      _defenseSettingList[index]['weekType'] = newValue;
    });
    debugPrint("防区设置开关状态已更新为: $newValue");
  }



  // 格式化星期文本显示
  // 格式化星期文本显示
  String _formatWeekText(String weekStr) {
    // 分割并去重
    List<String> weekdays = weekStr.split('、').toSet().toList();

    // 定义所有星期的集合
    const allDaysSet = {'周一', '周二', '周三', '周四', '周五', '周六', '周日'};

    // 判断是否包含所有7天
    bool containsAllDays = weekdays.length == 7 &&
        weekdays.every((day) => allDaysSet.contains(day));

    // 判断是否只包含周末
    bool isWeekend = weekdays.length == 2 &&
        weekdays.contains('周六') &&
        weekdays.contains('周日');
    if (containsAllDays) {
      return "每天";
    } else if (isWeekend) {
      return "周末";
    } else {
      return weekStr;
    }
  }



}